require 'yaml'
IRCBot::Plugin.define "regmacro" do
	help_string 'Does regex-based macros. Check for macros using "regmacro rcheck <message>", set regex-macros using "regmacro set <regex>=<output>", and get stats on macros using "regmacro stats". Delete the last triggered one with "regmacro delete_last".'
	@macros = YAML::load(File.open($config['global']['plugin_data_dir']+'/regex_macros.yml')) if File.exists?($config['global']['plugin_data_dir']+'/regex_macros.yml')
	if !@macros then @macros = {}; end
	@macrotime = {}
	@last_triggered = ""
	TIMEOUT = 300
	
	def macrologic(phrase)
		triggers = []
		for macro in @macros
			if phrase =~ Regexp.new(macro[0]) then
				triggers.push macro[0]
			end
		end
		trigger = triggers.sort[-1]
		macro = @macros[trigger]
		time = @macrotime[trigger]
		return [trigger,macro,time]
	end
	
	
	def reverse_macrologic(message)
		triggers = []
		for macro in @macros
			if macro[1] and !macro[1].empty? and message.downcase.include?(macro[1].downcase) then
				triggers << macro[0]
			end
		end
		trigger = triggers.sort[-1]
		macro = @macros[trigger]
		time = @macrotime[trigger]
		return [trigger,macro,time]
	end
	
	def privmsg_function(user,target,message,hostmask)
		macro = macrologic(message)
		if macro[0] and !macro[1].strip.empty? and !message.start_with?("#{$config['global']['command_identifier']}macro check ") then
			if !macro[2] or (Time.new - macro[2]) >= TIMEOUT then
				output = macro[1].gsub('$nick',user).gsub('$NICK',user.upcase)
				if output.start_with?('/me ') then
					output = output.sub('/me ','')
					privmsg(target,1.chr+'ACTION '+output+1.chr)
				else
					privmsg(target,output)
				end
				@macrotime[macro[0]] = Time.new
				@last_triggered = macro[0]
			end
		end
	end
	
	def command(user,target,message,hostmask)
		command = message.split[0]
		message = message.sub(command,"").strip
		
		case command
			when 'set'
				if message =~ /^(.+?)=(.+?)/ or message =~ /^(.+?)=$/ then
					input = message.split('=')[0]
					output = message.sub(message.split('=')[0]+'=','')
					
					if output.end_with?("\n") then output.chomp!; end
					
					fail = false
					begin
						ted = Regexp.new(input)
					rescue RegexpError
						privmsg(target,"Regex failure!")
						privmsg(target,"Correct arguments and resubnit.")
						fail = true
					end
					if !fail then
						if input.downcase != input then
							privmsg(target,"That regex contains uppercase chars. It'll never trigger. Not adding.")
						elsif input.length >= 5 then
							@macros[input] = output
							File.open($config['global']['plugin_data_dir']+'/regex_macros.yml','w') do |f|
								f << @macros.to_yaml
							end
							privmsg(target,"Regex added!")
						else
							privmsg(target,"That regex is too short!")
						end
					end
				else
					privmsg(target,"Incorrect usage! Use as \"macro set input=output\"")
				end
			when 'delete_last'
				@macros.delete @last_triggered
				privmsg(target,"Last regex deleted.")
				File.open($config['global']['plugin_data_dir']+'/regex_macros.yml','w') do |f|
					f << @macros.to_yaml
				end
			when 'rcheck'
				macro = reverse_macrologic(message)
				if macro[0] and !macro[1].strip.empty? then
					if !macro[2] then
						privmsg(target,"The regex \"#{macro[0]}\" triggers the macro \"#{macro[1]}\".")
					elsif (Time.new - macro[2]) >= TIMEOUT then
						privmsg(target,"The regex \"#{macro[0]}\" triggers the macro \"#{macro[1]}\".")
					else
						timeout = (Time.new.to_i() - macro[2].to_i()).to_i
#						timeout = Time.new.to_i - timeout
						timeout = timeout - TIMEOUT
						timeout = timeout*(-1)
						privmsg(target,"The regex \"#{macro[0]}\" can trigger the macro \"#{macro[1]}\" in #{timeout} seconds.")
					end
				else
					privmsg(target,"\"#{message}\" can't be triggered by anything.")
				end
			when 'stats'
				privmsg(target,"I know of #{@macros.count} macros. Of these, #{@macrotime.count} have been been activated since I last started. The last triggered macro was \"#{@last_triggered}\".")
			else
				privmsg(target,"Were you trying to set a macro? Use \"regmacro set\".")
		end
	end
end
